﻿using System;
using System.Collections.Generic;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.IO;
using System.Globalization;
using System.Drawing.Imaging;
using System.Drawing;
using System.Configuration;
using System.Diagnostics;

namespace ImageProcessing.Utility
{
    public class ImagesHandler
    {
        //base directory
        private string _baseDir = @"D:\netbyte\image-handler";
        public string BaseDIR
        {
            get { return _baseDir; }
            set { _baseDir = value; }
        }
        //image archive directory
        private string _imageArchiveDir = @"F:\Images\Temp1";
        public string ImageArchiveDir
        {
            get { return _imageArchiveDir; }
            set { _imageArchiveDir = value; }
        }
        //image import directory
        private string _imageImportDir = @"D:\netbyte\ftp_root\turners\branches\ns_images";
        public string ImageImportDir
        {
            get { return _imageImportDir; }
            set { _imageImportDir = value; }
        }
        //image processed directory
        private string _imageProcessedDir = @"D:\netbyte\image-handler\images\processed";
        public string ImageProcessedDir
        {
            get { _imageProcessedDir = _baseDir + @"\processed"; return _imageProcessedDir; }
        }

        private string _watermarkPath;
        public string WaterMarkPath
        {
            get { _watermarkPath = _baseDir + @"\tal_trans_logo.png"; return _watermarkPath; }
        }

        private Image _watermarkImage = null;
        public Image GetWaterMarkImage()
        {
            if (_watermarkImage == null)
            {
                _watermarkImage = Image.FromFile(_watermarkPath);
            }
            return _watermarkImage;
        }

        public static int ratioWidth = 4;
        public static int ratioHeight = 3;

        //public static int LARGEIMGWIDTH = 640;
        //public static int MIDDLEIMGWIDTH = 480;
        public static int GALLERYVIEWIMGWIDTH = 284;
        public static int THUMBNAILIMGWIDTH = 132;//80;
        public static int ARCHIVEIMGWIDTH = 1024;
        public static int PROCESSEDLARGE = 800;

        private Database _db;
        private void ValidationPathAndFiles()
        {
            if (!Directory.Exists(_baseDir))
            {
                throw new Exception(string.Format("BaseDIR {0} is not valid.", _baseDir));
            }
            else if (!Directory.Exists(ImageImportDir))
            {
                throw new Exception(string.Format("ImageImportDir {0} is not valid.", _imageImportDir));
            }
            else if (!Directory.Exists(ImageProcessedDir))
            {
                throw new Exception(string.Format("ImageProcessedDir {0} is not valid.", _imageProcessedDir));
            }
            else if (!File.Exists(WaterMarkPath))
            {
                throw new Exception(string.Format("WatermarkPath {0} is not valid.", _watermarkPath));
            }
        }
        public ImagesHandler() {
            ValidationPathAndFiles();
            _db = Database.Open("turnersims");
        }
        public ImagesHandler(string dbname) {
            ValidationPathAndFiles();
            _db = Database.Open(dbname);
        }
        /// <summary>
        /// the constructor for create a new image handler object.
        /// </summary>
        /// <param name="basedir">the output images base directory</param>
        /// <param name="importdir">the original images base directory (the username subfolder parent folder)</param>
        /// <param name="archivedir">the archive folder (required for existing sharepoint 2007 turners site)</param>
        public ImagesHandler(string basedir,  string importdir, string archivedir)
        {
            _baseDir = basedir;
            _imageArchiveDir = archivedir;
            _imageImportDir = importdir;
            _db = Database.Open("turnersims");
            ValidationPathAndFiles();
        }
        public ImagesHandler(string basedir, string importdir, string archivedir,string dbname)
        {
            _baseDir = basedir;
            _imageArchiveDir = archivedir;
            _imageImportDir = importdir;
            _db = Database.Open(dbname);
            ValidationPathAndFiles();
        }

        public List<string> GetImportFiles()
        {
            string[] files = Directory.GetFiles(_imageImportDir, "*.jpg");
            List<string> result = new List<string>();
            result.AddRange(files);
            return result;
        }
        public List<string> GetBatchProcessFiles(string batchProcessDir)
        {
            string[] files = Directory.GetFiles(batchProcessDir, "*.jpg", SearchOption.AllDirectories);
            List<string> result = new List<string>();
            result.AddRange(files);
            return result;
        }

        /// <summary>
        /// save the backup images to year week folder in the archive folder
        /// upload the images from archive folder
        /// </summary>
        /// <param name="isArchived"></param>
        /// <returns></returns>
        public bool ProcessToYearWeek(bool isArchived)
        {
            string current_year_week_dir = getCurrentProcessedDirectory();

            string currentProcessedYearDir = _imageProcessedDir + @"\" + DateTime.Now.Year;
            string currentProcessedDir = _imageProcessedDir + @"\" + current_year_week_dir;
            CreateFolderIfNotExist(currentProcessedYearDir);
            CreateFolderIfNotExist(currentProcessedDir);

            string archiveDir = string.Empty;
            if (isArchived)
            {
                string currentArchiveYearDir = _imageArchiveDir + @"\" + DateTime.Now.Year;
                string currentArchiveDir = _imageArchiveDir + @"\" + current_year_week_dir;
                CreateFolderIfNotExist(currentArchiveYearDir);
                CreateFolderIfNotExist(currentArchiveDir);
                archiveDir = currentArchiveDir;
            }

            
            List<string> importFiles = GetImportFiles();

            try
            {
                CreateLargeImageAndThumbnail(importFiles, currentProcessedDir, archiveDir);
            }
            catch (Exception)
            {
                return false;
            }
            return true;
        }
        /// <summary>
        /// images will be processed and saved to MD5 folder in Processed folder
        /// and archived images will be saved to archive folder under file structure (year)/week + (weeknumber).
        /// </summary>
        /// <param name="isArchived"></param>
        /// <returns></returns>
        public bool ProcessToMD5(bool isArchived)
        {
            string archiveDir = string.Empty;
            if (isArchived)
            {
                string current_year_week_dir = getCurrentProcessedDirectory();

                string currentArchiveYearDir = _imageArchiveDir + @"\" + DateTime.Now.Year;
                string currentArchiveDir = _imageArchiveDir + @"\" + current_year_week_dir;
                CreateFolderIfNotExist(currentArchiveYearDir);
                CreateFolderIfNotExist(currentArchiveDir);
                archiveDir = currentArchiveDir;
            }
            List<string> importFiles = GetImportFiles();
            try
            {
                foreach (string item in importFiles)
                {
                    PhotoInfo info = LoadFile(item); 
                    DatabaseUpdate(info);
                    CreateLargeImageAndThumbnail(item, info.DestinationPath, archiveDir);
                }
            }
            catch (Exception)
            {
                return false;
            }
            return true;
        }

        /// <summary>
        /// images will be 
        /// 1. processed and saved to MD5 folder in Processed folder
        /// 2. temp archived images will be saved to archive folder under file structure yyyyMMddHHmm
        /// 3. if isArchived is true, all images will be transferred to ftp site
        /// </summary>
        /// <param name="isArchived"></param>
        /// <returns></returns>
        public bool ProcessToMD5AndArchiveToTimeFolder(bool isTAMOSSActive)
        {
            string archiveDir = string.Empty;

            //EventLog.WriteEntry("PhotoDecoding", String.Format("archive to FTP: {0}", isTAMOSSActive), EventLogEntryType.Information);
            Trace.Write("isTAMOSSActive : " + isTAMOSSActive);
            string timeFolder = DateTime.Now.ToString("yyyyMMddHHmm");

            //EventLog.WriteEntry("PhotoDecoding",String.Format("local directory is created {0}",archiveDir), EventLogEntryType.Information);

            List<string> importFiles = GetImportFiles();
            List<string> archiveFiles = new List<string>();

            try
            {
                if(importFiles.Count > 0)
                {
                    string currentArchiveDir = _imageArchiveDir + @"\" + timeFolder;
                    CreateFolderIfNotExist(currentArchiveDir);
                    archiveDir = currentArchiveDir;                
                    foreach (string item in importFiles)
                    {

                        string filename = GetFileName(item);
                        archiveFiles.Add(filename);
                        PhotoInfo info = LoadFile(item);
                        DatabaseUpdate(info);
                        CreateLargeImageAndThumbnail(item, info.DestinationPath, archiveDir);
                    }
                    //upload the images from archive folder to SharePoint server TAMOSS01
                    if(isTAMOSSActive)
                    {
                        Trace.Write("Number of archive Files: " + archiveFiles.Count);
                        UploadImagesToFtpMossSite(archiveDir, archiveFiles);
                    }                
                }
            }
            catch (Exception)
            {
                return false;
            }
            return true;
        }

        public bool BatchProcessToMD5AndArchiveToTimeFolder(bool isTAMOSSActive, 
                                                            bool toBeArchived, 
                                                            string batchProcessDir, 
                                                            string batchUploadDir, 
                                                            out TimeSpan ftpDuration)
        {
            string archiveDir = string.Empty;
            ftpDuration = new TimeSpan();
            string timeFolder = DateTime.Now.ToString("yyyyMMddHHmm");
            if(toBeArchived)
            {
                
                string currentArchiveDir = _imageArchiveDir + @"\" + timeFolder;
                CreateFolderIfNotExist(currentArchiveDir);
                archiveDir = currentArchiveDir;
            }
            List<string> importFiles = GetBatchProcessFiles(batchProcessDir);
            List<string> archiveFiles = new List<string>();
            try
            {
                foreach (string item in importFiles)
                {

                    string filename = GetFileName(item);
                    archiveFiles.Add(filename);
                    PhotoInfo info = LoadFile(item);
                    DatabaseUpdate(info);
                    CreateLargeImageAndThumbnail(item, info.DestinationPath, archiveDir);
                }
                //upload the images from archive folder to SharePoint server TAMOSS01
                if (isTAMOSSActive)
                {
                    DateTime uploadStart = DateTime.Now;

                    List<string> uploadFiles = GetBatchProcessFiles(batchUploadDir);
                    List<string> fileNames = new List<string>();
                    foreach (string uploadFile in uploadFiles)
                    {
                        fileNames.Add(GetFileName(uploadFile));
                    }
                    List<string> errors = UploadImagesToFtpMossSite(batchUploadDir,fileNames);

                    DateTime uploadFinish = DateTime.Now;
                    TimeSpan duration = uploadFinish - uploadStart;
                    ftpDuration = duration;
                    if (errors.Count > 0)
                    {
                        string logMessage = "Error occurs on FTP upload to MOSS Site: <br />";
                        foreach (string error in errors)
                        {
                            logMessage += error + "<br />";
                        }
                        EventLog.WriteEntry("PhotoDecoding",logMessage, EventLogEntryType.Error);
                        return false;
                    }
                }
            }
            catch (Exception)
            {
                return false;
            }
            return true;
        }

        //reload database basic information from processed images
        public void UpdateDatabaseFromProcessedImages(string processFolder)
        {
            string[] files = Directory.GetFiles(processFolder, "*.jpg", SearchOption.AllDirectories);
            foreach (string file in files)
            {
                string filename = GetFileName(file);
                if (filename.EndsWith(".jpg", StringComparison.CurrentCultureIgnoreCase))
                {
                    string goodId = string.Empty;
                    string suffix = string.Empty;
                    string pattern = @"^(\d+)([A-Za-z]+)_thumb.jpg$";

                    Match match = Regex.Match(filename, pattern);
                    if (match.Success)
                    {
                        goodId = match.Groups[1].Value;
                        suffix = match.Groups[2].Value;

                        string md5 = Util.GetMD5(goodId);
                        string md5Folder1 = md5.Substring(0, 2);
                        string md5Folder2 = md5.Substring(2, 2);

                        string folder = md5Folder1 + "\\" + md5Folder2;
                        DatabaseUpdate(new PhotoInfo{GoodID = goodId, Suffix = suffix,MD5Folder = folder, LoadTime = DateTime.Now});
                    }
                }
            }

        }

        private List<string> UploadImagesToFtpMossSite(string archiveDir, IEnumerable<string> archiveFiles)
        {
            var errorUploadMessage = new List<string>();

            string currentYearWeekDir = getCurrentProcessedDirectoryWeb(DateTime.Now);
            string ftpUrl = ConfigurationManager.AppSettings["FtpUrl"];
            if (!ftpUrl.EndsWith("/"))
            {
                ftpUrl = ftpUrl + "/";
            }
            // e.g. http://10.0.0.1/2012/Week10
            ftpUrl = ftpUrl + currentYearWeekDir;

            string ftpUsername = ConfigurationManager.AppSettings["FtpUsername"];
            string ftpUserPwd = ConfigurationManager.AppSettings["FtpUserPwd"];


            //if (!FtpDirectoryExists(ftpUrl, ftpUsername, ftpUserPwd))
            //{
            //    Trace.Write("Directory does not exist.");
            //    MakeDirectory(ftpUrl, ftpUsername, ftpUserPwd);
            //    Trace.Write("Directory is created.");
            //}
            CreateDirectoryIfNotExist(ftpUrl, ftpUsername, ftpUserPwd);

            foreach (string archiveFile in archiveFiles)
            {
                string pattern = @"^(\d+)([A-Za-z]+).jpg$";
                string destinationFileName = archiveFile;
                Match match = Regex.Match(archiveFile, pattern);
                if(match.Success)
                {
                    string goodId = match.Groups[1].Value;
                    string suffix = match.Groups[2].Value;
                    if(suffix.Length == 2)
                    {
                        suffix = suffix.Substring(1);
                    }
                    destinationFileName = string.Format("{0}{1}.jpg", goodId, suffix);
                }
                string itemFtpUrl = ftpUrl + @"/" + destinationFileName;
                string sourceItemPath = archiveDir + @"\" + archiveFile;
                try
                {
                    var request = (FtpWebRequest)WebRequest.Create(itemFtpUrl);
                    request.Method = WebRequestMethods.Ftp.UploadFile;

                    request.Credentials = new NetworkCredential(ftpUsername, ftpUserPwd);

                    byte[] fileContents = File.ReadAllBytes(sourceItemPath);
                    request.ContentLength = fileContents.Length;
                    using (Stream stream = request.GetRequestStream())
                    {
                        stream.Write(fileContents, 0, fileContents.Length);
                    }


                    var response = (FtpWebResponse)request.GetResponse();
                    response.Close();
                }
                catch (Exception ex)
                {
                    errorUploadMessage.Add(sourceItemPath);
                }
            }
            return errorUploadMessage;
        }

        private bool FtpDirectoryExists(string dirPath, string ftpUser, string ftpPassword)
        {
            bool isExists = true;
            try
            {
                var request = (FtpWebRequest)WebRequest.Create(dirPath);
                request.Credentials = new NetworkCredential(ftpUser, ftpPassword);
                request.Method = WebRequestMethods.Ftp.PrintWorkingDirectory;

                using (var response = (FtpWebResponse)request.GetResponse())
                {
                    isExists = true;
                }
                EventLog.WriteEntry("PhotoDecoding", "Directory already exist", EventLogEntryType.Information);
            }
            catch (Exception ex)
            {
                isExists = false;
                EventLog.WriteEntry("PhotoDecoding", "FTP Directory doesn't exist.", EventLogEntryType.Information);

            }
            return isExists;
        }

        private void MakeDirectory(string dirPath, string ftpUsername, string ftpPassword)
        {
            WebRequest request = WebRequest.Create(dirPath);
            request.Method = WebRequestMethods.Ftp.MakeDirectory;
            request.Credentials = new NetworkCredential(ftpUsername, ftpPassword);
            var resp = (FtpWebResponse)request.GetResponse();
            resp.Close();
        }

        private static void CreateDirectoryIfNotExist(string dirPath, string ftpUsername, string ftpPassword)
        {
            try
            {
                WebRequest request = WebRequest.Create(dirPath);
                request.Method = WebRequestMethods.Ftp.MakeDirectory;
                request.Credentials = new NetworkCredential(ftpUsername, ftpPassword);
                var resp = (FtpWebResponse)request.GetResponse();
                resp.Close();
            }
            catch (Exception)
            {
            }
        }

        private void DatabaseUpdate(PhotoInfo info)
        {

            _db.InsertUpdateImage(info.GoodID, info.Suffix, info.MD5Folder);
            _db.UpdateImagesCameraModelAndResolution(info.Width, info.Height, info.CameraModel, info.GoodID, info.Suffix);
        }

        private void GetGoodIdAndSuffix(string input, out string goodId, out string suffix)
        {
            goodId = string.Empty;
            suffix = string.Empty;
            string pattern = @"^(\d+)([A-Za-z]+)$";

            Match match = Regex.Match(input, pattern);
            if (match.Success)
            {
                goodId = match.Groups[1].Value;
                suffix = match.Groups[2].Value;
            }
        }
        /// <summary>
        /// Load the file informations and create the destination folders if doesn't exist yet
        /// </summary>
        /// <param name="item">the source full path of the image</param>
        private PhotoInfo LoadFile(string item)
        {
            PhotoInfo info = new PhotoInfo();

            string filename = GetFileName(item);
            if (filename.EndsWith(".jpg", StringComparison.CurrentCultureIgnoreCase))
            {
                filename = filename.Substring(0, filename.LastIndexOf("."));
            }
            string goodid, suffix;
            GetGoodIdAndSuffix(filename,out goodid,out suffix);
            //string goodid = filename.Substring(0, filename.Length - 1);
            //string suffix = filename.Substring(filename.Length - 1, 1);
            info.GoodID = goodid;
            info.Suffix = suffix;
            string md5 = Util.GetMD5(goodid);
            string md5Folder1 = md5.Substring(0, 2);
            string md5Folder2 = md5.Substring(2, 2);
            info.MD5Folder = md5Folder1 + "\\" + md5Folder2;

            string currentProcessedDir1 = _imageProcessedDir + @"\" + md5Folder1;
            string currentProcessedDir2 = currentProcessedDir1 + @"\" + md5Folder2;
            CreateFolderIfNotExist(currentProcessedDir1);
            CreateFolderIfNotExist(currentProcessedDir2);
            info.DestinationPath = currentProcessedDir2;


            System.Drawing.Image originalImage = System.Drawing.Image.FromFile(item);
            info.CameraModel = GetImageCameraModel(originalImage);
            info.Width = originalImage.Width;
            info.Height = originalImage.Height;

            originalImage.Dispose();
            return info;
        }

        /// <summary>
        /// create original image (size 1024) without watermark to archived folder
        /// create large image (640) with watermark to processed folder, naming conversion goodID + suffix + "_640".jpg
        /// create small size (480) with watermark to processed folder, naming conversion goodID + suffix + "_480".jpg
        /// create thumbnail image (80x60) with no watermark to processed folder, naming conversion goodID + suffix + "_thumb".jpg
        /// create Gallery view image (284x213) with watermark to processed folder, naming conversion goodId + suffix + "_284".jpg
        /// </summary>
        /// <param name="file"></param>
        /// <param name="isArchived"></param>
        /// <param name="processedDirectory"></param>
        /// <param name="archivedDirectory"></param>
        private void CreateLargeImageAndThumbnail(string file,string processedDirectory, string archivedDirectory)
        {
            Image watermarkImage = GetWaterMarkImage();
            string filename = GetFileName(file);
            System.Drawing.Image originalImage = System.Drawing.Image.FromFile(file);
            ImageExt original = ImageExt.Load(originalImage);

            //save resized image to processed folder

            //Gallery View Image - water mark
            ImageExt galleryImage;
            if (original.Width <= GALLERYVIEWIMGWIDTH)
            {
                galleryImage = original.Resize(ratioWidth, ratioHeight, original.Width).Watermark(watermarkImage, WaterMarkPosition.BOTTOMRIGHT, 5);
            }else
                galleryImage = original.Resize(ratioWidth, ratioHeight, GALLERYVIEWIMGWIDTH).Watermark(watermarkImage, WaterMarkPosition.BOTTOMRIGHT, 5);

            string galleryFilePath = processedDirectory + @"\" + Get284Name(filename);
            galleryImage.SaveJpeg(galleryFilePath);
            galleryImage.Dispose();

            //ImageExt middleImage;
            //if (original.Width <= MIDDLEIMGWIDTH)
            //{
            //    middleImage = original.Resize(ratioWidth, ratioHeight, original.Width).Watermark(watermarkImage, WaterMarkPosition.BOTTOMRIGHT, 5);
            //}
            //else
            //    middleImage = original.Resize(ratioWidth, ratioHeight, MIDDLEIMGWIDTH).Watermark(watermarkImage, WaterMarkPosition.BOTTOMRIGHT, 5);

            //string middleImagePath = processedDirectory + @"\" + Get480Name(filename);
            //middleImage.SaveJpeg(middleImagePath);
            //middleImage.Dispose();

            //save resized thumbnail image to processed folder

            //Thumbnail Image - no water mark
            ImageExt thumbnailImage = original.Resize(ratioWidth, ratioHeight, THUMBNAILIMGWIDTH);
            string thumbnailPath = processedDirectory + @"\" + GetThumbnailName(filename);
            thumbnailImage.SaveJpeg(thumbnailPath);
            thumbnailImage.Dispose();

            // largest processed image - water mark
            ImageExt processedLargeImage;

            if(originalImage.Width > PROCESSEDLARGE)
            {
                processedLargeImage = original.Resize(ratioWidth, ratioHeight, PROCESSEDLARGE).Watermark(
                    watermarkImage, WaterMarkPosition.BOTTOMRIGHT, 5);
            }else
            {
                processedLargeImage = original.Resize(ratioWidth, ratioHeight, original.Width).Watermark(
                    watermarkImage, WaterMarkPosition.BOTTOMRIGHT, 5);
            }
            string processedLargeImageFilePath = processedDirectory + @"\" + filename;
            processedLargeImage.SaveJpeg(processedLargeImageFilePath);
            processedLargeImage.Dispose();

            // archived largest image - no water mark
            ImageExt archiveImage;

            //if archiveDirectory is not empty
            //Save archive image to archive folder
            string archiveFilePath = archivedDirectory + "\\" + filename;
            if (originalImage.Width > ARCHIVEIMGWIDTH)
            {
                archiveImage = original.Resize(ratioWidth, ratioHeight, ARCHIVEIMGWIDTH);
                //archiveImage.SaveJpeg(processedDirectory + @"\" + filename);
                
                if(!string.IsNullOrEmpty(archivedDirectory))
                    archiveImage.SaveJpeg(archiveFilePath);
                archiveImage.Dispose();
            }
            else
            {
                //original.SaveJpeg(processedDirectory + @"\" + filename);
                
                if(!string.IsNullOrEmpty(archivedDirectory))
                    original.SaveJpeg(archiveFilePath);
            }


            original.Dispose();
            originalImage.Dispose();
        }
        private string GetThumbnailName(string filename)
        {
            int dotIndex = filename.LastIndexOf('.');
            string fileId = filename.Substring(0, dotIndex);
            return fileId + "_thumb.jpg";
        }
        //size of 480 and 640 is not needed anymore.
        private string Get480Name(string filename)
        {
            int dotIndex = filename.LastIndexOf('.');
            string fileId = filename.Substring(0, dotIndex);
            return fileId + "_480.jpg";
        }
        private string Get640Name(string filename)
        {
            int dotIndex = filename.LastIndexOf('.');
            string fileId = filename.Substring(0, dotIndex);
            return fileId + "_640.jpg";
        }
        private string Get284Name(string filename)
        {
            int dotIndex = filename.LastIndexOf('.');
            string fileId = filename.Substring(0, dotIndex);
            return fileId + "_284.jpg";
        }
        private void PerformSuffixHandling(string item)
        {
            
        }


        private void CreateLargeImageAndThumbnail(List<string> importFiles, string processedDirectory, string archivedDirectory)
        {

            foreach (string file in importFiles)
            {
                CreateLargeImageAndThumbnail(file, processedDirectory, archivedDirectory);
            }
        }

        private string GetFileName(string file)
        {
            string filename = file.Substring(file.LastIndexOf('\\') + 1, file.Length - file.LastIndexOf('\\') - 1);
            return filename;
        }

        private string GetImageCameraModel(System.Drawing.Image img)
        {
            PropertyItem[] propItems = img.PropertyItems;
            System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
            PropertyItem cameraType = null;
            foreach (PropertyItem item in propItems)
            {
                if (item.Id == 272)
                {
                    cameraType = item;
                    break;
                }
            }
            //get camera type from Exif metadata
            if (cameraType != null)
            {
                return encoding.GetString(cameraType.Value);
            }
            return string.Empty;
        }




        /// <summary>
        /// TODO: process the file suffix and update database
        /// </summary>
        /// <param name="importFiles"></param>
        private void PerformSuffixHandling(List<string> importFiles)
        {
            foreach (var item in importFiles)
            {
                PerformSuffixHandling(item);
            }
        }

        private void CreateFolderIfNotExist(string dirPath)
        {
            if (!Directory.Exists(dirPath))
            {
                Directory.CreateDirectory(dirPath);
            }
        }
        /// <summary>
        /// return the year/weeknumber directory for the destination directory
        /// </summary>
        /// <returns></returns>
        private string getCurrentProcessedDirectory() {
            DateTime current = DateTime.Now;
            return getCurrentProcessedDirectory(current);
        }
        private string getCurrentProcessedDirectory(DateTime current)
        {
            DateTimeFormatInfo dtfi = DateTimeFormatInfo.CurrentInfo;
            Calendar calendar = dtfi.Calendar;

            return calendar.GetYear(current) + @"\Week" + calendar.GetWeekOfYear(current,dtfi.CalendarWeekRule,dtfi.FirstDayOfWeek);
        }
        private string getCurrentProcessedDirectoryWeb(DateTime current)
        {
            DateTimeFormatInfo dtfi = DateTimeFormatInfo.CurrentInfo;
            Calendar calendar = dtfi.Calendar;

            //EventLog.WriteEntry("PhotoDecoding", String.Format("current date: {0}, current year:{1}, current week number: {2}", current.ToString("yyyy-MM-dd"), calendar.GetYear(current), calendar.GetWeekOfYear(current, dtfi.CalendarWeekRule, dtfi.FirstDayOfWeek)), EventLogEntryType.Information);
            return calendar.GetYear(current) + @"/Week" + calendar.GetWeekOfYear(current, CalendarWeekRule.FirstFullWeek, DayOfWeek.Monday);
        }
    }

}